package com.aphrodite.ui.canvas;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import com.aphrodite.image.ImageScaling;
import com.aphrodite.image.ImageUtil;
import com.aphrodite.util.BitmapFont;

/**
 * MAC OSX based desktop interface set the ICON_WIDTH ,ICON_HEIGHT variables
 * based on the width and height of the icons in the icon script
 * 
 * @author kentelt
 */
public class MacScreenCanvas extends Canvas {
	private BitmapFont bigFont;
	private boolean canPaintSubMenu = false;
	private final int HEIGHT = this.getHeight();
	// y pos of the desktop icons @ 78% of screen ht
	private int deskIcon_Y = HEIGHT * 78 / 100;
	// number of desktop icons
	private int deskIconCount;
	// start drawing the desktop icons from this value
	private int deskIconStart;

	// width of a single desktop icon
	private int deskIconWidth;
	private int fontHeight;
	// -------------------- sub menu variables-----------------------//

	// space between the desktop icons
	private int iconsPadding;
	private Image imgSubMenu;

	// private Image imgBanner;
	private Image imgTray;
	private boolean isSelectorInSubMenu = false;

	protected MacScreenMenu[] menu;
	private int menuIndex;
	// treat the selector also like a menu item
	private MacScreenMenu selector;
	// height to raise the selected icon on the desktop
	private int selPadding = (HEIGHT * 3 / 100);// (HEIGHT * 2.5 /
	// 100);// 6;
	private int subMenuHeight = 0;
	// width of the sub menu icons , for now set it to the desktop icon width
	private int subMenuIconPadding = 2;
	private int subMenuIndex = 1;
	// height of the sub menu icons , for now set it to the desktop icon height
	private int subMnuIcnHght;

	private int subMnuIcnWdth;
	private final int WIDTH = this.getWidth();

	/**
	 * Mac screen menu canvas
	 * 
	 * @param menu
	 *            Menu Schema
	 * @param imgTray
	 *            The image of the tray that contains the icons
	 * @param selectorImage
	 *            image to be used as the icon selector
	 * @param menuIcons
	 *            Icons should have same with (different heights are OK). The
	 *            last icon in the array should be the selector icon.
	 * @param imgSubMenu
	 *            Icons that should be used for the submenu
	 * @param font
	 *            Bitmap font instance
	 */
	// public MacScreenCanvas(MacScreenMenu[] menu, Image imgTray, Image[]
	// menuIcons, Image selectorImage,
	// Image imgSubMenu, BitmapFont font) {
	// try {
	// System.out.println("[MacScreen,init]Home screen constructor");
	// this.menu = menu;
	// this.bigFont = font;
	// this.imgSubMenu = imgSubMenu;
	// fontHeight = bigFont.getHeight();
	// this.imgTray = imgTray;
	// if (menuIcons.length != menu.length) {
	// throw new
	// IllegalArgumentException("No selector image in the menuIcons Image array"
	// );
	// }
	// setupIconLayout(menuIcons[0].getWidth());
	// System.out.println("[MacScreen,init] desk icons length " + menu.length);
	// Image rpt = ImageUtil.getImage("res/dsmenu.png");
	// for (int i = 0; i < this.menu.length; i++) {
	// this.menu[i].setMenuImage(menuIcons[i]);
	// this.menu[i].setIconXPos(deskIconStart + (deskIconWidth * i) +
	// (iconsPadding * i));
	// this.menu[i].setIconYPos(deskIcon_Y);
	// setCaptionDim(menu[i]);
	// if (this.menu[i].hasSubmenu()) {
	// for (int j = 0; j < this.menu[i].getSubmenu().length; j++) {
	// this.menu[i].getSubmenu()[j].setMenuImage((this.menu[i].getSubmenu()[j].
	// isReport()) ? rpt
	// : imgSubMenu);
	// setCaptionDim(this.menu[i].getSubmenu()[j]);
	// }
	// }
	// }
	// selector = new MacScreenMenu(null);
	// selector.setMenuImage(selectorImage);
	// System.out.println("[MacScreen]Home screen constructor complete!");
	// } catch (Exception e) {
	// System.out.println("Exception in mac screen " + e.toString());
	// }
	// }
	public MacScreenCanvas(MacScreenMenu[] menu, Image imgTray, Image[] menuIcons, Image selectorImage,
			Image imgSubMenu, BitmapFont font) {
		try {
			this.menu = menu;
			this.bigFont = font;
			this.imgSubMenu = imgSubMenu;
			fontHeight = bigFont.getHeight();
			this.imgTray = imgTray;
			deskIcon_Y = getHeight() - menuIcons[0].getHeight() - imgTray.getHeight() / 2;
			// TODO review image scaling
			int trayTargetHeight = (int) ((12.5 * HEIGHT) / 100);
			if (imgTray.getWidth() != WIDTH) {
				this.imgTray = ImageScaling.doBresenhamScale(imgTray, WIDTH, trayTargetHeight, true);
			}
			if (menuIcons.length != menu.length) {
				throw new IllegalArgumentException("No selector image in the menuIcons Image array");
			}
			setupIconLayout(menuIcons[0].getWidth());
			System.out.println("[MacScreen,init] desk icons length " + menu.length);
			// TODO review image scaling
			Image rptImage = ImageUtil.getImage("res/dsmenu.png");
			// int rptImageTargetW = (int) (getWidth() * 10 / 100);
			// int rptImageTargetH = (int) (getHeight() * 13.3 / 100);
			// if (rptImage.getWidth() != rptImageTargetW ||
			// rptImage.getHeight() != rptImageTargetH) {
			// rptImage = ImageScaling.doBresenhamScale(rptImage,
			// rptImageTargetW, rptImageTargetH, true);
			// }
			for (int i = 0; i < this.menu.length; i++) {
				this.menu[i].setMenuImage(menuIcons[i]);
				this.menu[i].setIconXPos(deskIconStart + (deskIconWidth * i) + (iconsPadding * i));
				this.menu[i].setIconYPos(deskIcon_Y);
				setCaptionDim(menu[i]);
				if (this.menu[i].hasSubmenu()) {
					for (int j = 0; j < this.menu[i].getSubmenu().length; j++) {
						this.menu[i].getSubmenu()[j].setMenuImage((this.menu[i].getSubmenu()[j].isReport()) ? rptImage
								: imgSubMenu);
						setCaptionDim(this.menu[i].getSubmenu()[j]);
					}
				}
			}
			selector = new MacScreenMenu(null);
			selector.setMenuImage(selectorImage);// menuIcons[menuIcons.length -
			// 1]);

		} catch (Exception e) {
			System.out.println("Exception in mac screen " + e.toString());
		}
	}

	// public void pointerPressed(int x, int y) {
	// int menuW = menu[0].getMenuImage().getWidth();
	// int menuH = menu[0].getMenuImage().getHeight();
	// for (int i = 0; i < menu.length; i++) {
	// int menuX = menu[i].getIconXPos();
	// int menuY = menu[i].getIconYPos();
	// if (GeomUtils.withinBounds(x, y, menuX, menuY, menuW, menuH)) {
	// if (menu[i].hasSubmenu()) {
	// toggleSubMenu();
	// }
	// }
	//
	// }
	// }

	protected void cleanUp() {
		// imgBanner = null;
		imgTray = null;
		imgSubMenu = null;
		menu = null;
		bigFont = null;

	}

	private void drawScreenBG(Graphics g) {
		/* draw the tray image */
		g.drawImage(imgTray, 0, HEIGHT - imgTray.getHeight(), 0);

	}

	// private void drawCaption(Graphics g, MacScreenMenu menu) {
	// g.setColor(0x000000);
	// g.fillRoundRect(menu.getCaptionXPos(), menu.getCaptionYPos(),
	// menu.getCaptionWidth(), menu.getCaptionHeight(),
	// 20, 20);
	// // adding padding to caption X,Y to center the text in the rounded
	// // rectangle. its half of the padding added to the stringWidth and
	// // stringHeight variables
	// g.setColor(0xffffff);
	// // if (bigFont != null)
	// bigFont.drawString(g, menu.getCaption(), menu.getCaptionXPos() + 3,
	// menu.getCaptionYPos() + 2, 0);
	// }
	//
	// private void drawIcon(Graphics g, MacScreenMenu menu) {
	// g.drawImage(menu.getMenuImage(), menu.getIconXPos(), menu.getIconYPos() -
	// selPadding, 0);
	// }

	protected int getMenuIndex() {
		return menuIndex;
	}

	protected int getSubMenuIndex() {
		return subMenuIndex - 1;
	}

	private int getTotalMenuItems(int menuIndex) {
		if (menu[menuIndex].hasSubmenu()) {
			return menu[menuIndex].getSubmenu().length;
		}
		return 0;
	}

	protected void hideSubMenu() {
		canPaintSubMenu = false;
		subMenuIndex = 1;
		isSelectorInSubMenu = false;
		subMenuHeight = 0;
		repaint();
	}

	protected boolean isInSubMenu() {
		return isSelectorInSubMenu;
	}

	protected boolean isSubMenuVisible() {
		return canPaintSubMenu;
	}

	protected void keyPressed(int keycode) {
		int code = getGameAction(keycode);
		switch (code) {
		case Canvas.LEFT:
			moveLeft();
			break;
		case Canvas.RIGHT:
			moveRight();
		case Canvas.UP:
			scrollSubMenuUp();
			break;
		case Canvas.DOWN:
			scrollSubMenuDown();
			break;
		case FIRE:
			break;

		}
	}

	protected void keyRepeated(int keycode) {
		keyPressed(keycode);
	}

	protected void moveLeft() {
		if (!canPaintSubMenu) {
			if (menuIndex > 0)
				menuIndex--;
			else
				menuIndex = deskIconCount - 1;

			int y = deskIcon_Y - (fontHeight + 12); // 4 +8 , 4 is the

			repaint(0, y, WIDTH, HEIGHT - y);
		}
	}

	protected void moveRight() {
		if (!canPaintSubMenu) {
			if (menuIndex == deskIconCount - 1) {
				menuIndex = 0;
			} else if (menuIndex >= 0 && menuIndex < deskIconCount - 1) {
				menuIndex++;
			}
			int y = deskIcon_Y - (fontHeight + 12); // 4 +8 , 4 is the
			// rectangular box
			// padding and 8 is the
			// raised
			// selected icon
			repaint(0, y, WIDTH, HEIGHT - y);
		}
	}

	/**
	 * @see javax.microedition.lcdui.Canvas#paint(javax.microedition.lcdui.Graphics)
	 */
	protected void paint(Graphics g) {
		drawScreenBG(g);
		g.setColor(0xffffff);
		// x pos of the desktop icons
		int deskIconX = 0;
		// start for
		// TODO remove
		Image temp = null;
		for (int i = 0; i < menu.length; i++) {
			// draw selector image if its the current
			if (i == menuIndex) {
				// draw the caption above the icon (in the center) if not
				// showing submenu
				if (!canPaintSubMenu) {
					int tempX = menu[i].getIconXPos() + (menu[i].getMenuImage().getWidth() / 2);
					tempX = tempX - (menu[i].getCaptionWidth() / 2);
					menu[i].setCaptionXPos(tempX, WIDTH);
					menu[i].setCaptionYPos(menu[i].getIconYPos() - (menu[i].getCaptionHeight() + 5));
					menu[i].drawCaption(g, bigFont);
					selector.setIconYPos(menu[i].getIconYPos() - selPadding);
				} else {
					selector
							.setIconYPos(menu[i].getIconYPos() - (selPadding + (subMenuIndex * imgSubMenu.getHeight())));
				}
				// raise the selected icon 8 pix above the rest
				selector.setIconXPos(menu[i].getIconXPos());
				selector.drawIcon(g);
				menu[i].setIconYPos(menu[i].getIconYPos() - selPadding);
				temp = menu[i].getMenuImage();
				// TODO remove
				menu[i].setMenuImage(ImageScaling.doBresenhamScale(temp, temp.getWidth() + 3, temp.getHeight() + 3,
						true));
			}
			menu[i].drawIcon(g);
			// reset the menu's y position
			menu[i].setIconYPos(deskIcon_Y);
		}
		menu[menuIndex].setMenuImage(temp);
		// end for

		if (canPaintSubMenu) {
			if (menu[menuIndex].hasSubmenu()) {
				MacScreenMenu[] subMenu = menu[menuIndex].getSubmenu();
				deskIconX = deskIconStart + (deskIconWidth * menuIndex) + (iconsPadding * menuIndex);
				g.setColor(0x808080);
				subMenuHeight = subMenu.length * (subMnuIcnHght + subMenuIconPadding);
				int subMenuWidth = subMnuIcnWdth;// + iconsPadding;
				g.drawRoundRect(deskIconX, deskIcon_Y - (selPadding + subMenuHeight), subMenuWidth,// +
						// iconsPadding
						subMenuHeight, 20, 20);
				g.setColor(0xffffff);

				if (isSelectorInSubMenu) {
					subMenu[subMenuIndex - 1].setSubMenuWidth(subMenuWidth + (iconsPadding * 3));
					subMenu[subMenuIndex - 1].setCaptionXPos(deskIconX + subMenuWidth, WIDTH);// +
					// (
					// iconsPadding
					// *
					// 3
					// )
					// )
					// ;
					subMenu[subMenuIndex - 1].setCaptionYPos(deskIcon_Y
							- ((subMnuIcnHght * subMenuIndex) + (subMenuIconPadding * subMenuIndex)));
					subMenu[subMenuIndex - 1].drawCaption(g, bigFont);
					// drawCaption(g, subMenu[subMenuIndex - 1]);
				}
				for (int i = 1; i <= subMenu.length; i++) {
					subMenu[i - 1].setIconXPos(deskIconX);// + iconsPadding);
					subMenu[i - 1].setIconYPos(deskIcon_Y - ((subMnuIcnHght * i) + (subMenuIconPadding * i)));
					subMenu[i - 1].drawIcon(g);
					// drawIcon(g, subMenu[i - 1]);
				}
			}
		}

	}

	protected void scrollSubMenuDown() {
		int subMenuItemCount = getTotalMenuItems(menuIndex);
		if (canPaintSubMenu) {
			if (subMenuIndex > 1) {
				subMenuIndex--;
				isSelectorInSubMenu = true;
			} else if (subMenuIndex == 1) {
				subMenuIndex--;
				isSelectorInSubMenu = false;// main menu icon is selected
			} else if (subMenuIndex == 0) {
				subMenuIndex = subMenuItemCount;
				isSelectorInSubMenu = true;
			}
			repaint();
		}
	}

	protected void scrollSubMenuUp() {
		int subMenuItemCount = getTotalMenuItems(menuIndex);
		if (canPaintSubMenu) {
			if (subMenuIndex < subMenuItemCount) {
				subMenuIndex++;
				isSelectorInSubMenu = true;
			} else {
				subMenuIndex = 0;
				isSelectorInSubMenu = false;
			}
			repaint();
		}
	}

	private void setCaptionDim(MacScreenMenu menu) {
		menu.setCaptionWidth(bigFont.stringWidth(menu.getCaption()) + 6);
		menu.setCaptionHeight(fontHeight + 4);
	}

	private void setupIconLayout(int iconWidth) {
		subMnuIcnHght = imgSubMenu.getHeight();
		subMnuIcnWdth = imgSubMenu.getWidth();
		// determine the desktop icons starting point
		deskIconCount = menu.length;
		deskIconWidth = iconWidth;
		int tmp = WIDTH - (deskIconCount * deskIconWidth);
		deskIconStart = tmp / 3;
		// space between desktop icons
		iconsPadding = deskIconStart / deskIconCount;
	}

	protected void toggleSubMenu() {
		System.out.println("Toggle SubMenu function");
		if (canPaintSubMenu) {// removed painted submenu
			hideSubMenu();
		} else {// paint the submenu
			canPaintSubMenu = true;
			isSelectorInSubMenu = true;
			subMenuHeight = 0;
			repaint();
		}
	}
}
